// H5 环境适配工具
export const isH5 = () => {
  // #ifdef H5
  return true
  // #endif
  // #ifndef H5
  return false
  // #endif
}

export const isMobile = () => {
  if (!isH5()) return true
  
  const userAgent = navigator.userAgent.toLowerCase()
  const mobileKeywords = ['mobile', 'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone']
  
  return mobileKeywords.some(keyword => userAgent.includes(keyword))
}

export const getStorageAdapter = () => {
  if (isH5()) {
    return {
      getStorageSync: (key: string) => {
        try {
          const value = localStorage.getItem(key)
          return value ? JSON.parse(value) : null
        } catch (e) {
          return null
        }
      },
      setStorageSync: (key: string, data: any) => {
        try {
          localStorage.setItem(key, JSON.stringify(data))
        } catch (e) {
          console.error('Storage write failed:', e)
        }
      },
      removeStorageSync: (key: string) => {
        try {
          localStorage.removeItem(key)
        } catch (e) {
          console.error('Storage remove failed:', e)
        }
      }
    }
  }
  
  return {
    getStorageSync: uni.getStorageSync,
    setStorageSync: uni.setStorageSync,
    removeStorageSync: uni.removeStorageSync
  }
}

export const showToastAdapter = (options: { title: string; icon?: string; duration?: number }) => {
  if (isH5()) {
    // H5 环境使用简单的提示
    const toast = document.createElement('div')
    toast.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 12px 20px;
      border-radius: 8px;
      font-size: 14px;
      z-index: 10000;
      max-width: 80%;
      text-align: center;
    `
    toast.textContent = options.title
    document.body.appendChild(toast)
    
    setTimeout(() => {
      document.body.removeChild(toast)
    }, options.duration || 2000)
  } else {
    uni.showToast(options)
  }
}

export const showModalAdapter = (options: {
  title?: string
  content?: string
  showCancel?: boolean
  success?: (res: { confirm: boolean; cancel: boolean }) => void
}) => {
  if (isH5()) {
    const result = confirm(`${options.title || ''}\n${options.content || ''}`)
    if (options.success) {
      options.success({ confirm: result, cancel: !result })
    }
  } else {
    uni.showModal(options)
  }
}